package com.example.studentvotesystem.service;

import com.example.studentvotesystem.entity.User;
import com.example.studentvotesystem.mapper.UserMapper;
import com.example.studentvotesystem.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User register(String username, String password, String realName) {
        // 检查用户名是否已存在
        User existUser = userMapper.selectByUsername(username);
        if (existUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 生成盐值
        String salt = UUID.randomUUID().toString().substring(0, 8);
        // 加密密码
        String encryptedPassword = MD5Util.md5(password + salt);

        User user = new User();
        user.setUsername(username);
        user.setPassword(encryptedPassword);
        user.setSalt(salt);
        user.setRealName(realName);

        userMapper.insert(user);
        return user;
    }

    public User login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }

        String encryptedPassword = MD5Util.md5(password + user.getSalt());
        if (!encryptedPassword.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        return user;
    }

    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }
}

